package priv.wjh.study.cloud.feign.api.config;

import feign.Util;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import priv.wjh.study.cloud.feign.api.JsonUtil;

/**
 * <h1>泛型入参解析</h1>
 *
 * @author wangjunhao
 **/
public class GenericArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasMethodAnnotation(GenericArgument.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String s = Util.toString(((ServletWebRequest) webRequest).getRequest()
                                         .getReader());
        // 获取请求头中的泛型标识
        String generic = webRequest.getHeader("generic");

        if (!StringUtils.hasLength(generic)) {
            return JsonUtil.fromJson(s, parameter.getParameterType());

        } else {
            try {
                GenericWrapper genericWrapper = JsonUtil.fromJson(s, GenericWrapper.class);
                Class<?> clazz = Class.forName(genericWrapper.getClassName());
                return JsonUtil.fromJson(genericWrapper.getBody(), clazz);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("参数类型错误: " + s);
            }
        }
    }
}
